<template>
  <div class="classroom-info-container">
    <h1>教室信息管理</h1>
    <el-card style="max-width: contents">

<el-input
  v-model="data.name"
  style="width: 240px"
  size="large"
  placeholder="请输入教室名称"
  clearable
  :rows="1"
  type="textarea"
/>

<el-button type="primary" plain style="margin-left: 15px;" @click="load()">搜 索</el-button>
<el-button plain @click="reset()">重 置</el-button>

<el-button type="primary" plain @click="() => { data.formData = { id: '', name: '', state: '可用', capacity: 0, address: '', equipment: '' }; data.dialogVisible = true; }">新 增</el-button>
<el-button type="success" plain @click="() => { if (data.selectedRows.length === 1) handleEdit(data.selectedRows[0]); else ElMessage.error('请选择一条记录进行编辑'); }">更 新</el-button>
<el-button type="danger" plain @click="handleDelete">删 除</el-button>

</el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="data.dialogVisible" :title="data.formData.id ? '编辑教室' : '新增教室'">
      <el-form :model="data.formData" :rules="formRules" ref="formRef" label-width="120px">
        <el-form-item label="教室名称" prop="name">
          <el-input v-model="data.formData.name" />
        </el-form-item>
        <el-form-item label="教室状态" prop="state">
          <el-select v-model="data.formData.state">
            <el-option label="可用" value="可用" />
            <el-option label="不可用" value="不可用" />
          </el-select>
        </el-form-item>
        <el-form-item label="教室容量" prop="capacity">
          <el-input v-model.number="data.formData.capacity" type="number" />
        </el-form-item>
        <el-form-item label="教室位置" prop="address">
          <el-input v-model="data.formData.address" />
        </el-form-item>
        <el-form-item label="教室设备" prop="equipment">
          <el-input v-model="data.formData.equipment" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="data.dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit()">确定</el-button>
      </template>
    </el-dialog>

    <el-table :data="data.tableData" 
    style="width: 100%; height: auto;" 
    stripe
    row-class-name="table-row-class"
    @selection-change="handleSelectionChange"
    @edit="handleEdit"
    @close="handleClose"
    @submit="handleSubmit"
    >
    <el-table-column type="selection" width="55" />
    <el-table-column fixed prop="id" label="ID" width="auto" />
    <el-table-column prop="name" label="教室名称" width="auto" />
    <el-table-column prop="state" label="教室状态" width="auto" />
    <el-table-column prop="capacity" label="教室容量" width="auto" />
    <el-table-column prop="address" label="教室位置" width="auto" />
    <el-table-column prop="equipment" label="教室设备" width="auto" />
    <el-table-column prop="operation" label="操作" width="200">
      <template slot-scope="scope">
        <el-button type="primary" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
        <el-button type="danger" size="mini" @click="() => { data.selectedRows = [scope.row]; handleDelete(); }">删除</el-button>
      </template>
    </el-table-column>

  </el-table>
  </div>

  <div class="demo-pagination-block">
    <div class="demonstration">All combined</div>
    <el-pagination
      v-model:current-page="data.currentPage"
      v-model:page-size="data.pageSize"
      :page-sizes="[10, 20, 30, 40]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="data.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

</template>

<script setup>
import { reactive, ref, onMounted } from 'vue';
import { ElMessage, ElDialog, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElButton } from 'element-plus';
import request from '@/utils/request';

const formRef = ref(null);

onMounted(() => {
  load();
});

const formRules = {
  name: [
    { required: true, message: '请输入教室名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  state: [
    { required: true, message: '请选择教室状态', trigger: 'change' }
  ],
  capacity: [
    { required: true, message: '请输入教室容量', trigger: 'blur' },
    { type: 'number', min: 1, message: '容量必须大于0', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入教室位置', trigger: 'blur' },
    { min: 5, message: '位置描述至少5个字符', trigger: 'blur' }
  ]
};

/**
 * 教室管理模块
 */
const data = reactive({
  tableData: [],
  total: 0,
  pageSize: 10,
  currentPage: 1,
  name: '',
  selectedRows: [],
  dialogVisible: false,
  formData: {
    id: '',
    name: '',
    state: '',
    capacity: '',
    address: '',
    equipment: '',
  },
});


/**
 * 加载教室列表
 */
const load = () => {
  console.log('开始加载数据，参数:', { pageNum: data.currentPage, pageSize: data.pageSize, name: data.name });
  request.get('/classroom/selectByPage', {
    params: {
      pageNum: data.currentPage,
      pageSize: data.pageSize,
      name: data.name,
    }
  }).then(res => {
    console.log('数据加载成功:', res.data);
    data.tableData = res.data.list || [];
    data.total = res.data.total || 0;
  }).catch(error => {
    console.error('数据加载失败:', error);
    ElMessage.error('数据加载失败: ' + (error.response?.data?.message || error.message || '未知错误'));
  });
};

/**
 * 重置查询条件
 */
const reset = () => {
  data.name = '';
  load();
};

/**
 * 分页大小改变
 */
const handleSizeChange = (val) => {
  data.pageSize = val;
  load();
};

/**
 * 分页页码改变
 */
const handleCurrentChange = (val) => {
  data.currentPage = val;
  load();
};


/**
 * 选中行改变
 * @param {*} val 
 */
const handleSelectionChange = (val) => {
  console.log('选中的行数据:', val);
  data.selectedRows = val;
};


/**
 * 新增教室
 */
const handleInsert = () => {
  if (!data.formData.name) {
    ElMessage.error('请输入教室名称');
    return;
  }
  request.post('/classroom/insert', data.formData)
    .then(res => {
      ElMessage.success('新增成功');
      data.dialogVisible = false;
      load();
    })
    .catch(error => {
      ElMessage.error('新增失败: ' + (error.response?.data?.message || error.message));
      console.error('数据新增失败:', error);
    });
};

/**
 * 打开编辑对话框
 */
const handleEdit = (row) => {
  data.formData = { ...row };
  data.dialogVisible = true;
};

/**
 * 更新教室
 */
const handleUpdate = () => {
  if (!data.formData.id) {
    ElMessage.error('无效的教室ID');
    return;
  }
  if (!data.formData.name) {
    ElMessage.error('请输入教室名称');
    return;
  }
  request.put('/classroom/update', data.formData)
    .then(res => {
      ElMessage.success('更新成功');
      data.dialogVisible = false;
      load();
    })
    .catch(error => {
      ElMessage.error('更新失败: ' + (error.response?.data?.message || error.message));
      console.error('数据更新失败:', error);
    });
};

/**
 * 删除教室
 */
const handleDelete = () => {
  if (data.selectedRows.length === 0) {
    ElMessage.error('请选择要删除的教室');
    return;
  }
  const ids = data.selectedRows.map(row => row.id);
  request.delete('/classroom/delete', { data: ids })
    .then(res => {
      ElMessage.success('删除成功');
      load();
    })
    .catch(error => {
      ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message));
      console.error('数据删除失败:', error);
    });
};


/**
 * 提交表单
 */
const handleSubmit = async () => {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
    if (data.formData.id) {
      await handleUpdate();
    } else {
      await handleInsert();
    }
    data.dialogVisible = false;
  } catch (error) {
    console.error('表单验证失败:', error);
    ElMessage.error('请完善表单信息后提交');
  }
};

/**
 * 重置表单数据
 */
const resetFormData = () => {
  data.formData = {
    id: '',
    name: '',
    state: '',
    capacity: '',
    address: '',
    equipment: '',
  };
};


/**
 * 关闭新增/编辑对话框
 */
const handleClose = () => {
  data.dialogVisible = false;
};



// 初始加载数据
load();


</script>

<style scoped>
/* 教室信息管理页面样式 */
.classroom-info-container {
  padding: 20px;
}
</style>